package com.xieshue.im.client.handler;

import com.xieshue.im.protocol.Command;
import com.xieshue.im.protocol.Message;
import com.xieshue.im.protocol.MessageProto;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;

/**
 * @author xieshue
 * @date 2017\12\12 0012
 */
public class ImClientChannelHandler extends ChannelHandlerAdapter {
    private static final Logger logger = LoggerFactory.getLogger(ImClientChannelHandler.class);

    /**
     * 空闲时执行的方法
     *
     * @param ctx
     * @param evt
     * @throws Exception
     */
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            IdleState state = ((IdleStateEvent) evt).state();
            if (state == IdleState.WRITER_IDLE) {
                MessageProto messageProto = MessageProto.newBuilder()
                        .setCommand(Command.PING)
                        .setMessage(Message.newBuilder().setBody("Heartbeat"))
                        .build();
                ctx.writeAndFlush(messageProto);
            }
        } else {
            super.userEventTriggered(ctx, evt);
        }
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("激活时间是：" + new Date());
        System.out.println("HeartBeatClientHandler channelActive:" + ctx.channel().id().toString());
        MessageProto messageProto = MessageProto.newBuilder()
                .setCommand(Command.LOGIN)
                .setMessage(Message.newBuilder().setBody("login"))
                .build();
        ctx.writeAndFlush(messageProto);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (logger.isDebugEnabled()) {
            logger.debug("收到服务端回执信息...");
        }
        System.out.println(ctx.channel().id().toString());
        if (msg instanceof MessageProto) {
            MessageProto response = (MessageProto) msg;
            if (response.getCommand() == Command.LOGIN) {
                System.out.println(response.getMessage().getBody());
            }
        }
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        super.channelInactive(ctx);
        System.out.println("停止时间是：" + new Date());
        System.out.println("HeartBeatClientHandler channelInactive");
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        logger.warn("" + cause.getMessage());
        ctx.close();
    }
}
